package com.zbkj.service.util;

import com.alibaba.fastjson.JSON;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.Payment;
import com.huifu.adapay.model.PaymentConfirm;
import com.huifu.adapay.model.PaymentReverse;
import com.huifu.adapay.model.Refund;
import com.zbkj.service.param.AdaPayParam;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class PaymentRegionAndRequestTimeOutUtil {


    /**
     * 执行一个支付交易
     *
     * @return 创建的支付对象
     * @throws Exception 异常
     */
    public static Map<String, Object> executePayment(AdaPayParam adaPayParam) throws Exception {
        //创建支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/index.html
        Map<String, Object> paymentParams = new HashMap<>(10);
        paymentParams.put("app_id", adaPayParam.getAppId());
        paymentParams.put("order_no", adaPayParam.getOrderNo());
        paymentParams.put("pay_channel", adaPayParam.getPayChannel());
        paymentParams.put("pay_amt", adaPayParam.getPayAmt());
        paymentParams.put("goods_title", adaPayParam.getGoodsTitle());
        paymentParams.put("goods_desc", adaPayParam.getGoodsDesc());
        paymentParams.put("notify_url", adaPayParam.getNotifyUrl());
        paymentParams.put("pay_mode", adaPayParam.getPayMode());
        paymentParams.put("expend", adaPayParam.getExpend());
        //调用sdk方法，创建支付，得到支付对象
        Map<String, Object> payment = new HashMap<>();
        try {
            log.info("支付交易，请求参数：{}", JSON.toJSONString(paymentParams));
            payment = Payment.create(paymentParams);

        } catch (BaseAdaPayException e) {
            e.printStackTrace();
        }
        log.info("支付交易，返回参数：{}", JSON.toJSONString(payment));
        log.info("=======execute payment end=======");
        return payment;
    }

    /**
     * 执行一个退款交易
     *
     * @param paymentId 要退款的原支付paymentId
     * @return 创建的退款对象
     * @throws Exception 异常
     */
    public static Map<String, Object> executeRefund(Map<String, Object> refundParams, String paymentId) throws Exception {
        Map<String, Object> response = Refund.create(paymentId, refundParams);

        return response;
    }

    /**
     * 执行一个退款交易
     *
     * @return 创建的退款对象
     * @throws Exception 异常
     */
    public static Map<String, Object> cancelPay(Map<String, Object> reverseParams) throws Exception {

        Map<String, Object> paymentReverse = PaymentReverse.create(reverseParams);
        return paymentReverse;
    }

    /**
     * 确认支付
     * @param reverseParams
     * @return
     * @throws BaseAdaPayException
     */
    public static Map<String, Object> confirmPay(Map<String, Object> reverseParams) throws BaseAdaPayException {

        log.info("确认支付，请求参数：{}", JSON.toJSONString(reverseParams));
        Map<String, Object> map = PaymentConfirm.create(reverseParams);
        return map;
    }
}
